<?php
namespace app\api\controller;
use think\facade\Db;

class Member extends Base
{
    protected $APPID;

    protected $SECRET;

    public function __construct()
    {
        $miniApp = Db::name("system")->where("config","miniapp")->find();
        $this->APPID = $miniApp["value"];
        $this->SECRET = $miniApp["extend"];
    }

    public function wxLogin()
    {
        $APPID =  $this->APPID;
        $SECRET = $this->SECRET;
        $code = input("code");
        $username = input("username");
        $avatar = input("avatar");

        $URL = "https://api.weixin.qq.com/sns/jscode2session";
        $data = ["appid" =>$APPID,"secret" => $SECRET ,"js_code" =>$code ,"grant_type" => "authorization_code"];
        $result = json_decode($this->httpRequest($URL, $data),true);
        $openId = $result['openid'];
        $userInfo = Db::name("user")->where("openid",$openId)->find();
        $sessionKey = md5(rand(10000,99999).time());
        if($userInfo){
            cache($sessionKey,  $openId);
            $data2["username"] = $username;
            $data2["avatar"] = $avatar;
            Db::name("user")->where("openid",$openId)->where("user_type",2)->update($data2);
            return json(["code" => 1 ,"sessionKey" =>$sessionKey]);
      
        }else{
            $data1["username"] = $username;
            $data1["avatar"] = $avatar;
            $data1["openid"] = $openId;
            $data1["user_type"] = 2;
            $data1["group_id"] = 2;
            $data1["create_time"] = time();
            $userInfo = Db::name("user")->insert($data1);
            if($userInfo){
                cache($sessionKey,  $openId);
                return json(["code" => 1 ,"sessionKey" =>$sessionKey]);
            }
        }
        return json(["code" => 0 ,"msg" =>"错误"]);
    }
  
    public function httpRequest($url,$data = null,$headers=array()){
        $curl = curl_init();
        if( count($headers) >= 1 ){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}